from django.shortcuts import render
from shopcar.models import Shopcar
from shopcar.serializers import ShopcarSerializer, ShopcarSerializer_Post
from rest_framework import viewsets, mixins, permissions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

# Create your views here.
# 购物车提供列表、添加、删除接口
class ShopcarViewset(
    viewsets.GenericViewSet,
    mixins.ListModelMixin,
    mixins.CreateModelMixin,
    mixins.DestroyModelMixin,
):
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = [JSONWebTokenAuthentication]

    def get_queryset(self):  #  单个用户可以有多个地址，所以使用get_queryset()而不是get_object()
        user = self.request.user
        queryset = Shopcar.objects.filter(shopcarowner=user)
        return queryset

    def perform_create(self, serializers):
        serializers.save(shopcarowner=self.request.user)

    def get_serializer_class(self):
        if self.action == "list":
            serializer_class = ShopcarSerializer
        else:
            serializer_class = ShopcarSerializer_Post

        return serializer_class
